<script setup lang="ts">
import userAvatar1 from "@@/assets/images/layouts/1202320.png"
import userAvatar2 from "@@/assets/images/layouts/1202321.png"
import img1 from "@@/assets/images/layouts/tu3.png"
import pic from "@@/assets/images/layouts/pic.png"
import goodGray from "@@/assets/images/layouts/good-gray.png";
import commentGray from "@@/assets/images/layouts/commentGray.png";
import shareGray from "@@/assets/images/layouts/shareGray.png";
import toDetail from "@@/assets/images/layouts/to-detail.png";
const goodImg = ref(goodGray)
const shareImg = ref(shareGray)
const commentImg = ref(commentGray)
const toDetailImg = ref(toDetail)
import { useUserStore } from "@/pinia/stores/user.js"
import {
  getCirclePostListByPageApi, getCirclePostReplyAllApi, sendReplyCommentApi
} from "@/api"
import { onBeforeMount, ref} from "vue"
import {removeToken} from "@@/utils/cache/cookies";
import Head from "@@/components/Head/index.vue"
import Footer from "@@/components/footer/index.vue"
import axios from 'axios';
const userStore = useUserStore()
const router = useRouter()
const dialogVisible = ref(false)
const route = useRoute()
const token = ref("")
const list = ref([]) // 5条推荐列表数据
const username = ref("")
const recomment = ref([]) // 多条评论的回复数组
const infoCommentDataList = ref([])
const uploadReferenceFile = ref([])
const commentRefList = ref([])
const selected_reply_comment_list = ref([])
const topRef = ref(null)
const currentCommentInputId = ref(null)
const formSendData = ref({
  id: null
})
const currentPage = ref(1)
const currentLimit = ref(5)
const showMore = ref(true)
const dialogCommentShowVisible = ref(false)
onBeforeMount(() => {
  // 组件已完成响应式状态设置，但未创建DOM节点
  username.value = userStore.getUserName().value
  token.value = userStore.token
  if (token.value === '') {
    dialogVisible.value = true
  }
  getCirclePostList()
})
function getCirclePostList() {
  // 获取帖子列表，带分页功能
  getCirclePostListByPageApi({ page: currentPage.value, limit: currentLimit.value, reply_Page: 1, reply_limit:3}).then((res) => {
    if (res.code == 0) {
      // 循环添加数据
      for (let i in res.data) {
        res.data[i].comment_img_list = res.data[i].comment_imgs == '' ? []: res.data[i].comment_imgs.split(",")
        res.data[i].content = res.data[i].commentcontent? res.data[i].commentcontent : ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.replaceAll('-','.'): ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.replaceAll(' ','-'): ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.substring(0,16): ''
        infoCommentDataList.value.push(res.data[i])
      }
      if ( Math.ceil(res.count / currentLimit.value) >= currentPage.value) {
        showMore.value = false
      }
    }
  })
}
function showCommentDialog(id: any) {
  commentRefList.value[id].style.display = `block`;
}
const selectedFile = ref(null);
const imageUrl = ref([])
const imageFileName = ref([])
function handleFileUpload(event) {
  console.log(currentCommentInputId.value)
  const files = event.target.files;
  console.log(files)
  if(files.length > 1) {
    ElMessage.error({ message: "一次最多上传9张图片", type: "warning", duration: 2000 })
  } else {
    for (let i in  files) {
      // 遍历文件列表，判断文件类型是否是图片
      if (files[i].type == 'image/jpeg' || files[i].type == 'image/png' || files[i].type == 'image/jpg' ) {
        if (files[i] && files[i].type) {
          selectedFile.value = files[i]; // 存储选中的文件，可以在这里做进一步处理，如上传等。
          // console.log(selectedFile.value); // 或者使用FormData发送文件等操作
          const formData = new FormData();
          formData.append('imgFile', selectedFile.value);
          try {
            axios.post('https://www.sacasaca.com/shop122/uploadfile', formData, {
              headers: { 'Content-Type': 'multipart/form-data' },
            }).then(response => {
              console.log(response.data.code)
              if(response.data.code == 0) {
                console.log(response.data.data.url)
                if(!imageUrl.value || !imageUrl.value[currentCommentInputId.value]) {
                  imageUrl.value[currentCommentInputId.value] = []
                  imageUrl.value[currentCommentInputId.value].push(response.data.data.url) ;
                } else {
                  imageUrl.value[currentCommentInputId.value].push(response.data.data.url) ;
                }
              } else {
                ElMessage.error({
                  message: "上传失败",
                  type: "warning",
                  duration: 2000
                })
              }
            })
          } catch (error) {
            console.error(error);
          }
        }
      }
    }
  }

}
function triggerFileInput(index) {
  currentCommentInputId.value =  index
  uploadReferenceFile.value[index].click();
}
function handleReComment(index) {
  // 提交评论的评论
  if( token.value == "" || userStore.getUserId().value == 0) {
    return ElMessage.error({
      message: "请先登录",
      type: "warning",
      duration: 2000
    })
  }
  // 处理上传的图片 commentImgList去除空元素
  if(imageUrl.value && imageUrl.value[index]) {
    imageUrl.value[index].forEach((item) => {
      if (item === "") {
        imageUrl.value[index].splice(imageUrl.value.indexOf(item), 1)
      }
    })
  }

  if (recomment.value[index] !== "") {
    const data2 = {
      source_id: infoCommentDataList.value[index].article_id,
      contents: recomment.value[index],
      user_id: userStore.getUserId().value,
      ctype: 1,
      img_list: imageUrl.value[index] ? imageUrl.value[index].join( ","): '', // 多图列表
      action: 2,
      parent_id: infoCommentDataList.value[index].comment_id
    }
    sendReplyCommentApi(data2).then((res) => {
      if (res.code === 0) {
        recomment.value[index] =  ""
        imageUrl.value[index] = []
        ElMessage.success({
          message: "回复评论成功",
          type: "success",
          duration: 1000
        })
      } else {
        ElMessage.error({
          message: "回复评论失败",
          type: "warning",
          duration: 2000
        })
      }
    })
  } else {
    ElMessage.error({
      message: "请输入评论内容",
      type: "warning",
      duration: 2000
    })
  }
}
function getMoreComment() {
  getCirclePostListByPageApi({ page: currentPage.value + 1, limit: currentLimit.value}).then((res) => {
    if (res.code == 0) {
      currentPage.value += 1
      // 循环添加数据
      for (let i in res.data) {
        res.data[i].comment_img_list = res.data[i].comment_imgs == '' ? []: res.data[i].comment_imgs.split(",")
        res.data[i].content = res.data[i].commentcontent? res.data[i].commentcontent : ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.replaceAll('-','.'): ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.replaceAll(' ','-'): ''
        res.data[i].create_time = res.data[i].create_time ? res.data[i].create_time.substring(0,16): ''
        infoCommentDataList.value.push(res.data[i])
      }
      if ( Math.ceil(res.count / currentLimit.value) >= currentPage.value) {
        showMore.value = false
      }
    }
  })
}
function getMoreReplyComment(id) {
  dialogCommentShowVisible.value = true
  getCirclePostReplyAllApi({comment_id: id}).then((res) => {
    console.log(res.data)
    if (res.code == 0) {
      const t = res.data
      if (t && t.length > 0) {
        t.forEach(item => {
          item.create_time = item.create_time ? item.create_time.replaceAll('-','.'): ''
          item.create_time = item.create_time ? item.create_time.replaceAll(' ','-'): ''
          item.create_time = item.create_time ? item.create_time.substring(0,16): ''
          // 处理图片数组
          if (item.comment_imgs && item.comment_imgs.length > 0) {
            item.comment_img_list = item.comment_imgs.split(',')
          } else {
            item.comment_img_list = []
          }
          selected_reply_comment_list.value.push(item)
        })
      }
    }
  })
}
function backToTop() {
  topRef.value.scrollIntoView({behavior: 'smooth'});
}
</script>

<template>
  <div class="comment-container" style="height: auto;">
    <Head :activeId="4" />
    <div class="module-container" ref="topRef" style="height: auto;">
      <div v-for="(infoCommentData,index) in infoCommentDataList" style="width: 100%;display: flex;min-height:562px;flex-direction: column;margin-top: 32px;background-color: white;border-radius: 8px;padding-left: 24px;padding-right: 24px;">
        <div style="width: 100%;display: flex;flex-direction: row;margin-top: 10px;height: 50px;line-height: 40px;margin-top: 8px;">
          <div style="width: 80%;display: flex;flex-direction: row;justify-content: flex-start;">
            <div style="width:60px;padding: 8px;" v-if="infoCommentData.avatar">
              <el-image :src="infoCommentData.avatar" width="60" height="60" class="avatar_photo"></el-image>
            </div>
            <div style="width:60px;padding: 8px;border-radius: 8px;" v-else-if="infoCommentData.user_head_ico == 1">
              <el-image :src="userAvatar1" width="60" height="60" class="avatar_photo"></el-image>
            </div>
            <div style="width:60px;padding: 8px;" v-else-if="infoCommentData.user_head_ico == 2">
              <el-image :src="userAvatar2" width="60" height="60" class="avatar_photo"></el-image>
            </div>
            <div style="width:60px;padding: 8px;" v-else>
              <el-image :src="img1" width="60" height="60" class="avatar_photo"></el-image>
            </div>
            <div style="width:100px;padding: 8px;">{{infoCommentData.user_name}}</div>
            <div style="width:600px;padding: 8px;"></div>
          </div>
          <div style="width: 20%;padding: 8px;">{{infoCommentData.create_time}}</div>
        </div>
        <div style="width:100%;">
          <div style="width: 98%;padding: 8px;font-size: 14px;line-height: 24px;text-indent: 24px;height: 60px;">
            <p>{{infoCommentData.commentcontent}}</p>
          </div>
        </div>
        <div style="width:100%;margin-top: 8px;" v-if="infoCommentData.comment_img_list">
          <div style="width: 98%;padding: 8px;display: flex;flex-direction: row;">
            <div v-for="item in infoCommentData.comment_img_list" class="comment_photo_div">
              <el-image :src="item" width="80" height="80" class="comment_photo"></el-image>
            </div>
          </div>
        </div>
        <div style="width:1152px;background-color: rgb(237 234 234 / 29%);border-radius:8px;height:208px;margin-top: 24px;display: flex;flex-direction: row;">
          <div style="width: 100%;padding: 0 0;display: flex;flex-direction: row;">
            <div class="article_photo1" v-if="infoCommentData.article_img != ''">
              <el-image :src="infoCommentData.article_img" width="160" height="160" class="article_photo"></el-image>
            </div>
            <div class="article_photo2">
              <div style="font-size:18px; font-weight: 500;margin-top: 24px;">{{infoCommentData.article_title}}</div>
              <div style="margin-top: 8px;text-align: justify ;line-height: 26px;font-size: 14px;font-weight: 400;color:#666666;" v-html="infoCommentData.article_description.substring(0,400)"></div>
            </div>
          </div>
          <div class="click_go">
            <div class="click_go_button">
                <router-link  target="_blank" :to="{ name: 'newsDetail', params: { id: infoCommentData.article_id } }">
                  <el-image :src="toDetailImg" width="24" height="24" class="to_detail_img"></el-image>
                </router-link>
            </div>
          </div>
        </div>
        <div style="width:100%;margin-top: 8px;">
          <div style="width: 98%;padding: 8px;display: flex;flex-direction: row;justify-content: flex-end;">
            <div style="width: 150px;display: flex;flex-direction: row;">
              <div class="img_list"  :style="{backgroundImage: 'url('+ goodImg +')'}"></div>
              <div class="goods-text">
                点赞 ({{infoCommentData.article_likes}})
              </div>
            </div>
            <div style="width: 150px;display: flex;flex-direction: row;" @click="showCommentDialog(index)">
              <div class="img_list"  :style="{backgroundImage: 'url('+ commentImg +')'}"/>
              <div class="goods-text">
                评论 ({{infoCommentData.article_comments}})
              </div></div>
            <div style="width: 150px;display: flex;flex-direction: row;">
              <div class="img_list"  :style="{backgroundImage: 'url('+ shareImg +')'}"/>
              <div class="goods-text">
                分享 ({{infoCommentData.article_shares}})
              </div>
            </div>
          </div>
        </div>

        <div class="comment-content2" ref="commentRefList" style="display: none;">
          <div class="comment-content2-2">
            <div class="comment-content2-2-column">
              <div class="comment-content2-avatar">
                <el-image :src="img1"  class="avatar_photo2"></el-image>
              </div>
              <div class="comment-content2-input">
                <el-input v-model="recomment[index]" style="width:98%;height: 40px;" placeholder="期待你的评论">
                  <template #suffix>
                    <input ref="uploadReferenceFile" style="display: none;" type="file" @change="handleFileUpload" multiple />
                    <el-button @click="triggerFileInput(index)" :style="{width: '18px', height: '18px', border: 0, backgroundImage: 'url(' + pic + ')', backgroundSize: 'contain', padding: '0'}"></el-button>
                  </template>
                </el-input>
              </div>
              <div class="comment-content2-submit">
                <el-button @click="handleReComment(index)" :disabled="!recomment || !recomment[index] || recomment[index].length == 0" type="primary" style="border-radius: 18px;padding: 8px 8px;width:90px;height: 38px;"> 提 交 </el-button>
              </div>
            </div>
          </div>
          <div class="comment-content2-pre-image">
            <div style="display: flex;flex-direction: row;">
              <div style="width:50px;height: 26px;"></div>
              <div v-for="item in imageUrl[index]" class="comment_pre_photo">
                <el-image :src="item" width="100" height="100" class="comment_pre_photo"></el-image>
              </div>
            </div>
          </div>
        </div>

        <div class="comment-content-second" v-if="infoCommentData.reply_comment_list && infoCommentData.reply_comment_list.length > 0"
             v-for="item2 in infoCommentData.reply_comment_list" >
          <div class="comment-content-second-left">
            <div class="comment-content-second-avatar">
              <div style="width:60px;padding: 8px;" v-if="item2.avatar">
                <el-image :src="item2.avatar" width="60" height="60" class="avatar_photo"></el-image>
              </div>
              <div style="width:60px;padding: 8px;border-radius: 8px;" v-else-if="item2.user_head_ico == 1">
                <el-image :src="userAvatar1" width="60" height="60" class="avatar_photo"></el-image>
              </div>
              <div style="width:60px;padding: 8px;" v-else-if="item2.user_head_ico == 2">
                <el-image :src="userAvatar2" width="60" height="60" class="avatar_photo"></el-image>
              </div>
              <div style="width:60px;padding: 8px;" v-else>
                <el-image :src="img1" width="60" height="60" class="avatar_photo"></el-image>
              </div>
            </div>
            <div class="comment-content-second-name">{{item2.user_name}}</div>
          </div>
          <div class="comment-content-second-right">
            <div class="comment-content-second-content">{{item2.recontents}}</div>
            <div class="comment-content-second-time">{{item2.create_time}}</div>
            <div class="comment-content-second-photo"></div>
          </div>
        </div>
        <div v-if="infoCommentData.reply_count > 3" class="comment-more" @click="getMoreReplyComment(infoCommentData.comment_id)">查看更多{{infoCommentData.reply_count }}条回复</div>
      </div>
      <div>
        <div class="comment-content-second-more" @click="getMoreComment" v-if="!showMore">加载更多</div>
        <div @click="backToTop" class="comment-content-second-more">回到顶部</div>
        <div class="comment-content-second-more" style="height: 20px;"></div>
      </div>
    </div>
    <Footer />
    <el-dialog title="评论" v-model="dialogCommentShowVisible" width="800" style="width: 1000px;">
      <div>
        <div class="comment-content-second" v-if="selected_reply_comment_list && selected_reply_comment_list.length > 0"
             v-for="item2 in selected_reply_comment_list" >
          <div class="comment-content-second-left">
            <div class="comment-content-second-avatar">
              <div v-if="item2.user_head_ico == '1'">
                <el-image :src="userAvatar1"  class="avatar_photo3"></el-image>
              </div>
              <div v-else-if="item2.user_head_ico == '2'">
                <el-image :src="userAvatar2"  class="avatar_photo3"></el-image>
              </div>
              <div v-else-if="item2.user_avatar !=''">
                <el-image :src="item2.user_avatar"  class="avatar_photo3"></el-image>
              </div>
              <div v-else>
                <el-image :src="img1"  class="avatar_photo2"></el-image>
              </div>
              <div style="width:100%;min-height: 28px;"></div>
            </div>
            <div class="comment-content-second-name">{{item2.user_name}}</div>
          </div>
          <div class="comment-content-second-right">
            <div class="comment-content-second-content">{{item2.recontents.substring(0, 140)}}</div>
            <div class="comment-content-second-time">{{item2.create_time}}</div>
            <div class="comment-content-second-photo" v-if="item2.comment_img_list && item2.comment_img_list.length > 0">
              <div v-for="photo_item in item2.comment_img_list" class="item_photo_row">
                <el-image :src="photo_item" class="reply_comment_photo" fit="cover"></el-image>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<style src="@/pages/PMS/style/index.css"  scoped></style>
<style>
.data_items {
  width: 100%;
  display: flex;
  flex-direction: row;
  margin-bottom: 20px;
.data_item {
  width: 42%;
}
}
.comment-more {
  width: 100%;
  display: flex;
  flex-direction: row;
  font-size: 18px;
  line-height: 24px;
  margin-bottom: 8px;
  justify-items: center;
  justify-content: center;
  color: #0E6EF6;
  cursor: pointer;
}
.avatar_photo {
  width: 48px;
  height: 48px;
  border-radius: 50%;
}
.comment_photo_div {
  max-width: 100px;
  width: 80px;
  text-align: center;
  height: 80px;
  overflow: hidden;
  border-radius: 8px;
}
.article_photo {
  width: 160px;
  height: 160px;
  border-radius: 8px;
}
.article_photo1 {
  max-width: 260px;
  padding-left: 24px;
}
.article_photo2 {
  display: flex;
  flex-direction: column;
  padding-left: 20px;
}
.avatar_photo3 {
  width: 48px;
  height: 48px;
  border-radius: 50%;
}
.comment_photo {
  width: 80px;
  height: 80px;
  border-radius: 8px;
}
.comment_pre_photo {
  width: 40px;
  height: 40px;
  margin-top: 2px;
  border-radius: 8px;
  display: grid;
  gap: 5px;
}
.img_list {
  margin-left: 12px;
  margin-right: 4px;
  width: 24px;
  height: 24px;
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: center center;
}
.goods-text {
  font-size: 18px;
  color: #333333;
  font-weight: 500;
  line-height: 26px;
}
.comment-content2-input {
  width: 100%;
  height: 40px;
}
.comment-content2 {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  line-height: 30px;
  padding: 5px 5px;
}
.comment-content2-2-column {
  width: 100%;
  display: flex;
  flex-direction: row;
}
.comment-content2-avatar {
  width: 40px;
  height: 40px;
  margin-right: 16px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.comment-content2-2 {
  min-width: 92%;
  height: auto;
  display: flex;
}
.comment-content2-pre-image {
  width: 600px;
  height: 50px;
  display: grid;

}
.comment-content2-submit {
  width: 180px;
  height: 40px;
  display: flex;
  flex-direction: row;
  margin-left: 12px;
}
.comment-content-second {
  width: 1200px;
  min-height: 100px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
.comment-content-second-left {
  width: 300px;
  display: flex;
  flex-direction: row;
.comment-content-second-name {
  font-size: 12px;
  color: #333;
  width: 60px;
  line-height: 20px;
}
.comment-content-second-avatar {
  width: 60px;
  height: 100px;
}
}
.comment-content-second-right {
  min-width: 96%;
  display: flex;
  flex-direction: column;
  justify-content:  flex-start;
.comment-content-second-time {
  font-size: 14px;
  color: #333;
  line-height: 24px;
}
.comment-content-second-photo{
  font-size: 14px;
  color: #333;
  line-height: 18px;
  height: 88px;
  display: flex;
  flex-direction: row;
  margin-right: 16px;
  margin-top: 8px;
  .item_photo_row {
    margin-right: 16px;
    .reply_comment_photo {
      width: 80px;
      height: 80px;
      border-radius: 8px;
    }
  }
}
}
}
.avatar_photo2 {
  width: 30px;
  height: 30px;
}
.comment-content-second-more {
  font-size: 18px;
  font-weight: 500;
  margin-top: 18px;
  line-height: 24px;
  color: #45A1FF;
  cursor: pointer;
}
.click_go {
  width:60px;
  height: auto;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  .click_go_button {
    width: 40px;
    height: 40px;
    cursor: pointer;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
}
</style>
